# -*- coding: utf-8 -*-

from __future__ import unicode_literals, print_function

import logging
import sys, os
import copy
import glob
import ConfigParser
import platform

import smvn.config as cfg
from smvn.util import write_rec, read_rec, pjoin
from smvn.core import get_all_info, Repo

updateinfo_cmd='cmake --build . --target update_buildinfo'

dr=Repo()

def help_handler(fmap, args):
    print(
"""
    cm:binfo [bdef [CMAKE_ARGS]]    check build env of a project
    cm:xbinfo [bdef|bs12 [cms12..]] cross compile build info
    cm:s12 [bs12 [CMAKE_ARGS]]      update Freescale s12 build info
    cm:build <bdef | barm ...>      make all target of the project
    cm:lbuild [CMAKE_ARGS]          make in the last dir
    cm:utest [all | comp1 comp2 ]   execute unittest files
    cm:bnt  [pom.xml]               build and run unittest for pom
    cm:ftest [cmd [args]]           execute functional test \
"""
    )

def ver_handler(fmap, args):
    print("0.0.1")

def show_clean_info():
    """
    show and clean build_info
    """
    if (os.path.exists(cfg.default_buildinfo_name)):
        with open(cfg.default_buildinfo_name) as bi:
            print('Current build info:', bi.read().strip())
        os.remove(cfg.default_buildinfo_name)

def exec_info_cmd(bdir, bcmds, save_env=True):
    """
    enter bdir, and exec list bcmds 
    """
    #print bdir, bcmds
    if not os.path.exists(bdir):
        os.makedirs(bdir)

    cpwd = os.getcwd()
    os.chdir(bdir)
    logging.info('>>>chdir '+bdir)
    if save_env: write_rec('SMVN_LAST_DIR', bdir)
    finalret = 0
    for cmd in bcmds:
        logging.info('>>>'+cmd)
        ret = os.system(cmd)
        if ret != 0:
            finalret += 1
    os.chdir(cpwd)
    return finalret

def get_info_param(args, defdir=cfg.DEFAULT_BDIR):
    """
    get all param info needs
    return 
        - bdir: dirname
        - bextra: extra arguments
        - brel: relative path to root
    """
    bdir = defdir
    bextra = ''
    if len(args) > 1:
        bdir = args[1]
        if len(args) > 2:
            bextra = ' '.join(args[2:])
    levels = len(bdir.replace('\\', '/').split('/'))
    cdinfo = '../'*levels
    brel = cdinfo[0:-1]
    return bdir, brel, bextra

def binfo_handler(fmap, args):
    show_clean_info()
    bdir, brel, bextra = get_info_param(args)
    init_cmd = 'cmake %s %s'%(bextra, brel)
    exec_info_cmd(bdir, [init_cmd, updateinfo_cmd])

def xbinfo_handler(fmap, args):
    """
     @brief 
        xbinfo s12
    """
    pass

def s12_handler(fmap, args):
    show_clean_info()
    bdir, brel, bextra = get_info_param(args, 'proj/bs12')
    exec_info_cmd(
        bdir, 
        ['cmake -G"MinGW Makefiles" -DCMAKE_TOOLCHAIN_FILE=%s/cm/s12x.cmake %s %s'%(brel, brel, bextra), 
         updateinfo_cmd])

def build_handler(fmap, args):
    """
    make default files
    """
    bdir, brel, bextra = get_info_param(args)
    cmdlist = ['cmake --build .']
    if not os.path.exists(pjoin(bdir, 'CMakeCache.txt')):
        cmdlist.insert(0, 'cmake '+brel)
    exec_info_cmd(bdir, cmdlist)

def lbuild_handler(fmap, args):
    """
    p, r = get_all_info(fmap, "pom.xml")
    cp = mycompiler('MSVC9', os.getcwd())
    cp.check_builddir()
    print(cp.compile())
    make in last dir
    """
    lastdir = read_rec('SMVN_LAST_DIR')

    exec_info_cmd(
        lastdir, 
        ['cmake --build . %s'%' '.join(args[1:])], 
        False)

def lmake_handler(fmap, args):
    """
    make in last dir
    """
    lastdir = read_rec('SMVN_LAST_DIR')

    exec_info_cmd(
        lastdir, 
        ['make %s'%' '.join(args[1:])], 
        False)

def bnt_handler(fmap, args):
    build_handler(fmap, args)
    utest_handler(fmap, args)

def utest_handler(fmap, args):
    """
     @brief 
    """
    p, r = get_all_info(fmap, "pom.xml")
    binpath = cfg.default_bin_path
    ret = 0

    if len(args) == 1:
        elem = p.artifactId
        if platform.system() != 'Windows': elem = './'+elem
        ret = exec_info_cmd( binpath, [elem+'_test'])
    elif len(args) >= 2:
        logging.info('unittest in %s', binpath)
        if args[1] == 'all':
            lexe_files = glob.glob(binpath+'/*_test'+cfg.exe_prefix)
            exe_files = [os.path.relpath(l, binpath) for l in lexe_files]
            for elem in exe_files:
                exec_info_cmd( binpath, [elem],)
        else:
            for elem in args[1:]:
                exec_info_cmd( binpath, [elem+'_test'])

def ftest_handler(fmap, args):
    binpath = cfg.default_bin_path
    if len(args) >= 2:
        exec_info_cmd(
            binpath, 
            args[1:],
        )

